package io.renren.modules.oss.cloud;

import io.renren.common.exception.RRException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 *本地存储
 */
public class LocalCloudStorageService  extends CloudStorageService {
  private static final Logger LOG = LoggerFactory.getLogger(LocalCloudStorageService.class);

  private String localUploadPath;

  public LocalCloudStorageService(CloudStorageConfig config){
    this.config = config;

    //初始化
    init();
  }

  private void init(){
    localUploadPath = config.getLocalUploadPath();
  }

  @Override
  public String upload(byte[] data, String path) {
      try {
        //将数组转为字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String str = encoder.encode(data).trim();
        //通过流写入文件夹
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imgbyte = decoder.decodeBuffer(str);
        //检查文件夹是否存在
        String localPath = config.getLocalUploadPath() + "/" + path;
        String uploadPath = localPath.substring(0,localPath.lastIndexOf("/"));
        File file = new File(uploadPath);
        if (!file.exists()) {
          file.mkdirs();
        }
        OutputStream os = new FileOutputStream(localPath);
        os.write(imgbyte, 0, imgbyte.length);
        os.flush();
        os.close();
      } catch (Exception e) {
          throw new RRException("上传文件失败，请核对文件服务配置信息", e);
      }
      return config.getLocalDomain() + "/" + path;
  }

  @Override
  public String upload(InputStream inputStream, String path) {
      try {
        byte[] data = IOUtils.toByteArray(inputStream);
        return this.upload(data, path);
      } catch (IOException e) {
        throw new RRException("上传文件失败", e);
      }
  }

  @Override
  public String uploadSuffix(byte[] data, String suffix) {
    return upload(data, getPath(config.getLocalFolder(), suffix));
  }

  @Override
  public String uploadSuffix(InputStream inputStream, String suffix) {
    return upload(inputStream, getPath(config.getLocalFolder(), suffix));
  }

  @Override
  public void delete(String url) {
      String path = url.substring(url.lastIndexOf(config.getLocalFolder()));
      String localPath = config.getLocalUploadPath() + "/" + path;
      File file = new File(localPath);
      if (file.isFile() && file.exists()) {
        file.delete();
      }
  }
}
